package com.zdcp.swagger2;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;

import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.WebMvcRequestHandler;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * API文档生成工具配置
 * @author yweijian
 * @date 2019年9月4日
 * @version 1.0
 */
@Configuration
@EnableSwagger2
public class Swagger2Config {
	
	/**
	 * 
	 * @return
	 */
	@Bean
	public Docket createRestApi() {
		return new Docket(DocumentationType.SWAGGER_2)
				.apiInfo(apiInfo())
				.select()
				.apis(basePackage(new String[]{"com.zdcp.web.controller","com.zdcp.generator.controller"}))
				.paths(PathSelectors.any())
				.build();
	}

	/**
	 * 构建 api文档的详细信息函数
	 * 
	 * @return
	 */
	private ApiInfo apiInfo() {
		return new ApiInfoBuilder()
				.title("ZDCP后台管理系统RESTful API测试工具")
				.version("1.0.0")
				.description("ZDCP后台管理框架采用shiro权限控制，BeetSql模板引擎，支持多数据源，简单快速搭建系统的脚手架 ").build();
	}
	
	/**
	 * 重写
	 * @param basePackage
	 * @return
	 */
	public static Predicate<RequestHandler> basePackage(final String[] basePackage) {
        return input -> declaringClass((WebMvcRequestHandler) input).transform(handlerPackage(basePackage)).or(true);
    }

    private static Function<Class<?>, Boolean> handlerPackage(final String[] basePackage)     {
        return input -> {
            for (String strPackage : basePackage) {
                boolean isMatch = input.getPackage().getName().startsWith(strPackage);
                if (isMatch) {
                    return true;
                }
            }
            return false;
        };
    }

    private static Optional<? extends Class<?>> declaringClass(WebMvcRequestHandler input) {
        return Optional.fromNullable(input.declaringClass());
    }
}
